package cn.edu.sctu.sctu_lysd.view.act;

import android.os.Handler;
import android.os.Message;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.UserProfile;
import cn.edu.sctu.sctu_lysd.biz.GetUserMessage;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.databinding.ActivityWelcomeBinding;
import cn.edu.sctu.sctu_lysd.presenter.WelcomePresenter;
import cn.edu.sctu.sctu_lysd.utils.JumpUtils;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;

/**
 * Created by wangfuxin on 2017-04-14.
 */

public class WelcomeAct extends BaseActivity implements GetUserMessage.View{

    private GetUserMessage.Presenter mPresenter;

    private Handler handler;

    private SharePreferenceUtils sharePreferenceUtils;

    private ActivityWelcomeBinding mBinding;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_welcome;
    }

    @Override
    protected void initAfter(Object bind) {

        mBinding = (ActivityWelcomeBinding) bind;

        initPresenter(new WelcomePresenter(this, this));

        sharePreferenceUtils = SharePreferenceUtils.getInstance(this);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                JumpUtils.jumpActivity(WelcomeAct.this, IndexActivity.class);
                finish();
            }

        };

        if (sharePreferenceUtils.ifHaveShare(CacheKeyConfig.CACHE_ACCESS_TOKEN)) {
            //没有登陆  不需要刷新 token
            mPresenter.refreshToken();

        } else {
            getUserProfileSuccess(null);

        }

    }

    @Override
    public void initPresenter(GetUserMessage.Presenter presenter) {

        this.mPresenter = presenter;

        mPresenter.start();

    }

    @Override
    public void getUserProfileSuccess(UserProfile data) {

        if (data != null) {
            mPresenter.getChatToken(data.getId());
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(2000);
                    handler.sendEmptyMessage(1);
                } catch (Exception e) {

                }
            }

        }).start();

    }

    @Override
    public void getUserProfileFailed() {

        sharePreferenceUtils.clearCache();

        getUserProfileSuccess(null);

    }

    @Override
    public void refreshTokenSuccess() {

        mPresenter.getUserProfile();

    }
    @Override
    public void refreshTokenFailed() {

        sharePreferenceUtils.clearCache();

        getUserProfileSuccess(null);

    }

    /**
     *获取chatToken成功后 链接融云
     */
    @Override
    public void getChatTokenSuccess(String chatToken) {
        connect(chatToken);
    }

    @Override
    public void getChatTokenFailed() {

    }
}
